import Block from "./Block"
import GridSystem from "../GridSystem"
import { BlockType, LinkMark } from "../Constants";
import IPoint from "../interface/IPoint";
class MyArrow extends Block {

    linkMark: LinkMark | null;
    linePoints: IPoint[];
    constructor(x: number, y: number, width: number, height: number, fill?: string) {
        super(x, y, width, height);
        this.class = BlockType.ARROW;
        this.linkMark = null;
        this.linePoints = [];
        this.cbTouch = false;
    }

    draw(x: number, y: number, width: number, height: number, angle?: number) {
        let ctx = GridSystem.gls.ctx;
        ctx.save()
        let { x: x1, y: y1 } = this.setAdsorption(x, y, width, height)
        x = x1;
        y = y1;
        let { x: x2, y: y2, angle: angle2 } = this.setPosAndAngleByLink(x, y, width, height, angle);  // 箭头独有
        x = x2;
        y = y2;
        angle = angle2;
        this.setAngle(x, y, width, height, angle)
        this.setSizeInfo(x, y, width, height)
        // ------ 公共部分

        ctx.beginPath();
        ctx.moveTo(x, y + height);
        ctx.lineTo(x + width / 2, y);
        ctx.lineTo(x + width, y + height);
        ctx.lineTo(x + width / 2, y + height / 1.5);
        ctx.closePath(); //闭合
        ctx.fillStyle = this.fill;	//再填充
        ctx.fill();	//再填充
        ctx.lineWidth = 1.5;
        ctx.strokeStyle = "#002766";
        ctx.stroke();
        ctx.restore()

        this.setFocusStyle();
        this.setControlPoints(x, y, width, height);
        this.isDraged = false;
        this.drawLink(x, y, width, height);
        this.update(x, y, width, height, angle)
    }

    // 根据线段最后两个值设置箭头的角度
    setPosAndAngleByLink(x: number, y: number, width: number, height: number, angle?: number) {
        if (this.linePoints && this.linePoints.length > 1) {
            // console.log("根据线段最后两个值设置箭头的角度");
            x = this.linePoints[this.linePoints.length - 1].x - width / 2;
            y = this.linePoints[this.linePoints.length - 1].y - height / 2;
            let curPoint, prePoint: IPoint;
            curPoint = this.linePoints[this.linePoints.length - 2];
            prePoint = this.linePoints[this.linePoints.length - 3];
            let vector = {
                x: curPoint.x - prePoint.x,
                y: curPoint.y - prePoint.y,
            }
            angle = Math.atan2(vector.y, vector.x) * 180 / Math.PI + 90;   //radians
        }
        return {
            x, y, angle
        }
    }
}

export default MyArrow;